package com.zego.zegowawaji_server;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.widget.Toast;

import com.bugtags.library.Bugtags;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.tinker.loader.app.DefaultApplicationLike;
import com.zego.base.utils.AppLogger;
import com.zego.base.utils.DeviceIdUtil;
import com.zego.base.utils.PrefUtil;
import com.zego.base.utils.TimeUtil;
import com.zego.manager.ModuleMgr;
import com.zego.zegoliveroom.ZegoLiveRoom;
import com.zego.zegoliveroom.constants.ZegoAvConfig;
import com.zego.zegoliveroom.constants.ZegoConstants;

/**
 * 热修复: Application代理类
 * Created by Su on 2018/3/26.
 */
public class AppTinkerLike extends DefaultApplicationLike {
    public AppTinkerLike(Application application, int tinkerFlags,
                         boolean tinkerLoadVerifyFlag, long applicationStartElapsedTime,
                         long applicationStartMillisTime, Intent tinkerResultIntent) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent);
    }


    @Override
    public void onCreate() {
        super.onCreate();
        // ======================= 自有逻辑 ============================
        sInstance = (ZegoApplication) getApplication();
        context = getApplication();
        deviceId = DeviceIdUtil.generateDeviceId(context);
        AppLogger.getInstance().writeLog("******* Application onCreate *******");
        ModuleMgr.initModule(getApplication());
        initUserInfo(); // first
        setupZegoSDK(); // last
        Bugtags.start("c57d9f34d04f2d7d27d62b25f5f0a79c", getApplication(), Bugtags.BTGInvocationEventNone);

        // 这里实现SDK初始化，appId替换成你的在Bugly平台申请的appId
        // 调试时，将第三个参数改为true
        Bugly.init(getApplication(), "61437f8eb3", false);
    }


    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        // you must install multiDex whatever tinker is installed!
        MultiDex.install(base);

        // 安装tinker
        // TinkerManager.installTinker(this); 替换成下面Bugly提供的方法
        Beta.installTinker(this);
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallback(Application.ActivityLifecycleCallbacks callbacks) {
        getApplication().registerActivityLifecycleCallbacks(callbacks);
    }

    // ========================= 自有逻辑 =============================================
    static final private long APP_ID = 2123036530;
    static final private byte[] APP_SIGN_KEY = new byte[]{
            (byte) 0x80, (byte) 0xd5, (byte) 0x16, (byte) 0xd1, (byte) 0xdd, (byte) 0xb5, (byte) 0xd0, (byte) 0x19,
            (byte) 0xd5, (byte) 0x58, (byte) 0x3f, (byte) 0xac, (byte) 0xb0, (byte) 0xfc, (byte) 0xb5, (byte) 0x5c,
            (byte) 0x38, (byte) 0xda, (byte) 0x89, (byte) 0xca, (byte) 0x84, (byte) 0xd5, (byte) 0xd2, (byte) 0x39,
            (byte) 0x4c, (byte) 0xb0, (byte) 0xf7, (byte) 0xe2, (byte) 0xb7, (byte) 0x10, (byte) 0x72, (byte) 0x97
    };
    public static String deviceId;
    public static Context context;
    static private ZegoApplication sInstance;
    private static ZegoLiveRoom mZegoLiveRoom;

    static public ZegoApplication getAppContext() {
        return sInstance;
    }

    public static Context getContext() {
        return context;
    }

    public static ZegoLiveRoom getZegoLiveRoom() {
        return mZegoLiveRoom;
    }

    /**
     * 设置用户信息
     */
    private void initUserInfo() {
        String userId = PrefUtil.getInstance().getUserId();
        String userName = PrefUtil.getInstance().getUserName();
        if (TextUtils.isEmpty(userId) || TextUtils.isEmpty(userName)) {
            userId = TimeUtil.getNowTimeStr();
            userName = String.format("WWJS_%s_%s", Build.MODEL.replaceAll(",", "."), userId);

            PrefUtil.getInstance().setUserId(userId);
            PrefUtil.getInstance().setUserName(userName);
        }
    }

    private void setupZegoSDK() {
        ZegoLiveRoom.setUser(PrefUtil.getInstance().getUserId(), PrefUtil.getInstance().getUserName());
        ZegoLiveRoom.requireHardwareEncoder(true);
        ZegoLiveRoom.requireHardwareDecoder(true);
        ZegoLiveRoom.setConfig("camera_orientation_mode=0");//设置视频方向
        ZegoLiveRoom.setTestEnv(true);    // 配置测试环境

        mZegoLiveRoom = new ZegoLiveRoom();
        mZegoLiveRoom.setSDKContext(new ZegoLiveRoom.SDKContext() {
            @Override
            public String getSoFullPath() {
                return null;
            }

            @Override
            public String getLogPath() {
                return null;
            }

            @Override
            public Application getAppContext() {
                return sInstance;
            }
        });

        initZegoSDK(mZegoLiveRoom);
    }

    private void initZegoSDK(ZegoLiveRoom liveRoom) {
        boolean success = liveRoom.initSDK(APP_ID, APP_SIGN_KEY);
        if (!success) {
            AppLogger.getInstance().writeLog("Init ZegoLiveRoom SDK failed");
            Toast.makeText(sInstance, "", Toast.LENGTH_LONG).show();
            return;
        }

        int resolutionLevel;
        ZegoAvConfig config;
        int level = PrefUtil.getInstance().getLiveQuality();
        if (level < 0) {
            // 默认设置级别为"标准"
            resolutionLevel = ZegoAvConfig.Level.Generic;

            config = new ZegoAvConfig(resolutionLevel);

            // 保存默认设置
            PrefUtil.getInstance().setLiveQuality(resolutionLevel);
            PrefUtil.getInstance().setLiveQualityResolution(resolutionLevel);
            PrefUtil.getInstance().setLiveQualityFps(15);
            PrefUtil.getInstance().setLiveQualityBitrate(600);
        } else if (level > ZegoAvConfig.Level.SuperHigh) {
            resolutionLevel = PrefUtil.getInstance().getLiveQualityResolution();

            config = new ZegoAvConfig(ZegoAvConfig.Level.High);
            config.setVideoBitrate(PrefUtil.getInstance().getLiveQualityBitrate());
            config.setVideoFPS(PrefUtil.getInstance().getLiveQualityFps());
        } else {
            resolutionLevel = level;
            config = new ZegoAvConfig(level);
        }

        String resolutionText = getApplication().getResources().getStringArray(R.array.zg_resolutions)[resolutionLevel];
        String[] strWidthHeight = resolutionText.split("x");

        int height = Integer.parseInt(strWidthHeight[0].trim());
        int width = Integer.parseInt(strWidthHeight[1].trim());
        config.setVideoEncodeResolution(width, height);
        config.setVideoCaptureResolution(width, height);

        liveRoom.setAVConfig(config);
        liveRoom.setAVConfig(config, ZegoConstants.PublishChannelIndex.AUX);
    }
}
